package com.jeect.config;

import com.jeect.service.impl.AuthenticationService;
import com.jeect.util.MyPasswordEncode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

//@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 需要放行的URL
     */
    private static final String[] AUTH_WHITELIST = {
            // -- register url
            "/user/"
            ,"/user/get/"
            ,"/user/userLogin"
            ,"/userlogin.html"
    };
   @Autowired
    private AuthenticationSuccessHandler demoAuthenticationSuccessHandler;
   @Autowired
   private AuthenticationFailureHandler authenticationFailureHandler;

   @Autowired
   private AuthenticationService authenticationService;
    @Autowired
   private MyPasswordEncode myPasswordEncode;
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        System.out.println("WebSecurityConfigurerAdapter........config().");
        http.formLogin().loginPage("/user/userLogin")
                .loginProcessingUrl("/user/login")
                .successHandler(demoAuthenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
//                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                //.addFilter(new JWTAuthorizationFilter(authenticationManager()))
                .authorizeRequests().antMatchers(AUTH_WHITELIST).permitAll()
                .and()
                // 不需要session
                //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
               // .and()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authenticationService).passwordEncoder(myPasswordEncode);
        super.configure(auth);
    }
}
